<?php


namespace app\controller\api;


use app\util\ReturnCode;
use think\Response;
use think\facade\Filesystem;
use think\exception\ValidateException;

class Upload extends Base
{
    // 本地单文件上传
    public function image(): Response {
        $file = request()->file('image');
        // 上传到本地服务器
        try {
            validate(['image'=>'fileSize:20480|fileExt:jpg,png,jpeg,JPG,PNG,JPEG'])
                ->check([$file]);
            $savename = Filesystem::disk('public')->putFile( date('Ymd', time()), $file, 'md5');
            return $this->buildSuccess([
                'fileName' => "/upload/".$savename,
                'fileUrl'  => $this->request->domain() ."/upload/". $savename
            ]);
        } catch (ValidateException $e) {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, '图片上传失败'.$e->getMessage());
        }

    }
    public function upload(): Response {
        $path = '/upload/' . date('Ymd', time()) . '/';
        $name = $_FILES['file']['name'];
        $tmp_name = $_FILES['file']['tmp_name'];
        $error = $_FILES['file']['error'];
        //过滤错误
        if ($error) {
            switch ($error) {
                case 1:
                    $error_message = '您上传的图片太大';
                    break;
                case 2:
                    $error_message = '您上传的图片太大';
                    break;
                case 3:
                    $error_message = '文件只被部分上传';
                    break;
                case 4:
                    $error_message = '文件不能为空';
                    break;
                default:
                    $error_message = '未知错误';
            }
            die($error_message);
        }
        $arr_name = explode('.', $name);
        $hz = array_pop($arr_name);
        $new_name = md5(time() . uniqid()) . '.' . $hz;
        if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $path)) {
            mkdir($_SERVER['DOCUMENT_ROOT'] . $path, 0755, true);
        }
        if (move_uploaded_file($tmp_name, $_SERVER['DOCUMENT_ROOT'] . $path . $new_name)) {
            return $this->buildSuccess([
                'fileName' => $path . $new_name,
                'fileUrl'  => $this->request->domain() . $path . $new_name
            ]);
        } else {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, '图片上传失败');
        }
    }
}